<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="650px"
  >
    <BasicForm @register="registerForm">
      <template #content="{ model, field }">
        <a-textarea v-if="model['infotype'] == 1" v-model:value="model[field]" :rows="4" />
        <div v-else>
          <a-upload-dragger
            :file-list="fileList"
            name="file"
            :maxCount="1"
            accept=".jpg,.png,.jpeg,.mp4"
            :custom-request="upload"
            @remove="removeFile"
            @change="changeFile"
            :showUploadList="{
              showRemoveIcon: true,
              showDownLoadIcon: true,
            }"
          >
            <!-- <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p> -->
            <p class="ant-upload-hint"> 请点击或拖拽上传图片 </p>
          </a-upload-dragger>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useGlobSetting } from '/@/hooks/setting';
  import { uploadApi } from '/@/api/platform/upload';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { getImageFileApi } from '/@/api/platform/file';
  import {
    addUnitStaticInfo,
    getUnitStaticInfo,
    updateUnitStaticInfo,
  } from '/@/api/ehs/unitDivision';
  import { addOrUpdateUnitStaticInfoSchema } from './unitDivision.data';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  const { createMessage } = useMessage();
  export default defineComponent({
    name: 'AddOrUpdateUnitStaticInfo',
    components: { BasicModal, BasicForm, CloudUploadOutlined },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const unitid = ref<String>('');
      const fileId = ref();
      const fileList = ref([]);
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema, clearValidate }] =
        useForm({
          labelWidth: 120,
          schemas: addOrUpdateUnitStaticInfoSchema,
          showActionButtonGroup: false,
          actionColOptions: {
            span: 24,
          },
        });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (data) {
            dataId.value = data.dataId;
            unitid.value = data.unitid;
          }
        }
        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });
        queryEnumOption('EhsUnitStaticinfoTypeEnum').then((res) => {
          let Options = [];
          for (let i of res[0].options) {
            Options.push({ value: Number(i.key), label: i.value });
          }
          updateSchema({
            field: 'infotype',
            componentProps: ({ formModel, formActionType }) => {
              return {
                allowClear: false,
                options: Options,
                onChange: (e) => {
                  console.log(e);
                  fileId.value = undefined;
                  fileList.value = [];
                  formActionType.setFieldsValue({
                    content: '',
                  });
                  clearValidate();
                },
              };
            },
          });
        });
        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (operateType.value == OperationTypeEnum.EDIT) {
          getStaticInfoById();
        }
      });
      /**
       * 返回弹窗标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      /**
       * 根据id获取静态信息
       */
      async function getStaticInfoById() {
        getUnitStaticInfo(dataId.value)
          .then((res) => {
            if (res.infotype !== 1) {
              fileId.value =
                res.content && JSON.parse(res.content).id ? JSON.parse(res.content).id : undefined;
              let content = JSON.parse(res.content);
              fileList.value =
                res.content && JSON.parse(res.content).id
                  ? [{ ...content, url: getImageFileUrlPrefix.value + content.url }]
                  : [];
              setFieldsValue({
                ...res,
                content: fileId.value,
              });
            } else {
              setFieldsValue({
                ...res,
              });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      function upload(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是svg或者png文件则上传,否则提示文件格式错误
        if (fileType === 'jpg' || fileType === 'png' || fileType === 'jpeg' || fileType === 'mp4') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                setFieldsValue({
                  content: res.data.data.fileid,
                });
                fileId.value = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
                clearValidate();
              } else {
                fileId.value = undefined;
                setFieldsValue({
                  content: null,
                });
                fileList.value[0].status = 'error';
                createMessage.error('上传失败,请稍后重试');
              }
            })
            .catch((err) => {
              fileId.value = undefined;
              setFieldsValue({
                content: null,
              });
              fileList.value[0].status = 'error';
              createMessage.error('上传失败,请稍后重试');
            });
        } else {
          fileId.value = undefined;
          fileList.value[0].status = 'error';
          setFieldsValue({
            content: null,
          });
          createMessage.error('文件格式不符,请上传jpg或png文件');
        }
      }
      function removeFile() {
        // 移除上传的文件,清空文件数据
        fileId.value = undefined;
        setFieldsValue({
          content: null,
        });
        fileList.value = [];
      }
      function changeFile(e) {
        fileList.value = e.fileList;
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validate();
        values.unitid = unitid.value;
        if (values.infotype !== 1) {
          console.log(fileId.value, fileList.value);
          values.content = fileId.value
            ? JSON.stringify({
                name: fileList.value[0]?.name,
                status: fileList.value[0]?.status,
                id: fileId.value,
                url: fileId.value,
              })
            : '';
        }
        setModalProps({ confirmLoading: true });
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addUnitStaticInfo({ ...values })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateUnitStaticInfo({ ...values })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
              // createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      onMounted(() => {});
      return {
        operateType,
        displayModuleTitle,
        fileId,
        fileList,
        registerModal,
        registerForm,
        getStaticInfoById,
        onButtonOkClick,
        opSuccess,
        upload,
        removeFile,
        changeFile,
      };
    },
  });
</script>

<style scoped></style>
